<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title> 随机动态球 </title>
	</head>
 <body>

	<canvas id="canvas" ></canvas>

<script>
window.onload = function () {

	const balls = [];
	const gravity = 0.5;
	const numBalls = 20;
	const canvas = document.getElementById('canvas');
	const context = canvas.getContext('2d');

	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	/**
	 *@Description
	 *@Return 添加80个小球放入的盒子中,位置.
    **/
	for (let ball, i = 0; i < numBalls; i++) {
		ball = new Ball(i + 1, Math.random() * 0xffffff); // 随机颜色
		ball.x  = canvas.width / 2; // 最高位置
		ball.y  = canvas.height; // 底部位置
		ball.vx = Math.random() * 2 - 1; // 随机x速度
		ball.vy = Math.random() * -10 - 10; // 随机y速度
		
		balls.push(ball); // 放入到盒子中
	}
	/**
	 *@Description
	 *@Return 绘制球.
    **/
	const draw = ball => {
		ball.vy += gravity;
		ball.x += ball.vx;
		ball.y += ball.vy;

		if(ball.x - ball.radius > canvas.width || ball.x + ball.radius < 0 || ball.y - ball.radius > canvas.height || ball.y + ball.radius < 0) {
			ball.x  = canvas.width / 2; // 最高位置
			ball.y  = canvas.height; // 底部位置
			ball.vx = Math.random() * 2 - 1; // 随机x速度
			ball.vy = Math.random() * -50; // 随机y速度
		}

		ball.draw(context);
	}	

	setInterval(() => {
		context.clearRect(0, 0, canvas.width, canvas.height);
		balls.forEach(draw);
	}, 30); 

}

// 下面这个代码赋值下
function Ball (radius, color) {
	if (radius === undefined) { radius = 40; }
	if (color === undefined) { color = "#ff0000"; }
	this.x = 0;
	this.y = 0;
	this.vx = 0;
	this.vy = 0;
	this.scaleX = 1;
	this.scaleY = 1;
	this.rotation = 0;
	this.lineWidth = 1;
	this.radius = radius;
	this.color = parseColor(color);
}

Ball.prototype.draw = function (context) {
	context.save();
	context.translate(this.x, this.y);
	context.rotate(this.rotation);
	context.scale(this.scaleX, this.scaleY);

	context.lineWidth = this.lineWidth;
	context.fillStyle = this.color;
	context.beginPath();

	// x, y, radius, start_angle, end_angle, anti-clockwise
	context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
	context.closePath();
	context.fill();
	if (this.lineWidth > 0) {
		context.stroke();
	}
	context.restore();
};

function parseColor (color, toNumber) {
	if (toNumber === true) {
		if (typeof color === 'number') {
			return (color | 0); // chop off decimal
		}

		if (typeof color === 'string' && color[0] === '#') {
			color = color.slice(1);
		}
		return window.parseInt(color, 16);

	} else {
		if (typeof color === 'number') {
			color = '#' + ('00000' + (color | 0).toString(16)).substr(-6); // pad
		}
		return color;
	}
};
</script>
 </body>
</html>
